# encoding=utf-8

from ExcelParser import load_book
from datetime import datetime
from VarDefine import *
import os
import re
import shutil

# 定义一个函数，用于筛选出指定文件夹中的所有图片文件
def get_all_images(folder_path):
    image_files = []
    files_last_name = []
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.lower().endswith((".png", ".jpg", ".jpeg", ".gif")):
                image_files.append(os.path.join(root, file))
                files_last_name.append(os.path.basename(file))

    return image_files,files_last_name

def get_file_modified_time(file_path):
    mod_time = os.path.getmtime(file_path)
    return datetime.fromtimestamp(mod_time)

# Folder序号含义
# Folder_1 未见明显糖尿病改变
#
# Folder_2 增殖性
#
# Folder_3   轻度非增殖
#
# Folder_4 中度非增殖
#
# Folder_5  重度非增殖
# 定义处理逻辑的函数
"""
workdir:
  Folder_1
   1.jpg
   xxxx.jpg
   .......
  Folder_2
   xxx.jpg
"""
def process_eye_data(eye_number, data, file_name):
    eye_prefix = "left" if eye_number == "0" else "right"
    eye_mapping = {
        1: "dr_un_ween",
        2: "dr_con",
        3: "dr_low_un_con",
        4: "dr_middle_un_con",
        5: "dr_high_un_con"
    }

    if data[eye_prefix] in eye_mapping:
        folder_path = f"workdir/Folder_{data[eye_prefix]}"
        out_path = os.path.join(folder_path, file_name)
        shutil.copy2(img_file, out_path)


def create_workdir_folder():
    os.makedirs("workdir", exist_ok=True)
    os.makedirs("workdir/Folder_1", exist_ok=True)
    os.makedirs("workdir/Folder_2", exist_ok=True)
    os.makedirs("workdir/Folder_3", exist_ok=True)
    os.makedirs("workdir/Folder_4", exist_ok=True)
    os.makedirs("workdir/Folder_5", exist_ok=True)


create_workdir_folder()
# 读取数据表格
# , limit=100
data_book = load_book("糖网筛查_20240403 090453.xlsx")

# 读取所有图片
input_path = "二院累计数据20240402"

# 计算匹配项目---------

# 创建存储文件夹
os.makedirs("Folder", exist_ok=True)

# 调用函数获取所有图片文件列表
image_files,files_last_name = get_all_images(input_path)

# 获取图像命名特征并复制图片文件*******************
# 打印所有筛选出的图片文件路径
for img_file,file_last_name in zip(image_files,files_last_name):
    mod_time = get_file_modified_time(img_file)
    converted_datetime_str1 = mod_time.strftime("%Y%m%d%H%M")
    for key, value in data_book.items():
        mytime_str = value["check_data"]
        # 将字符串转换为 datetime 对象
        mytime = datetime.strptime(mytime_str, "%Y-%m-%d %H:%M:%S")
        # 格式化输出为指定格式的字符串
        converted_datetime_str2 = mytime.strftime("%Y%m%d%H%M")
        folder_time = mytime.strftime("%Y%m%d%H%M%S")
        # print("data的:", converted_datetime_str2)
        if converted_datetime_str1 == converted_datetime_str2:
            # print(value["name"])
            second_character = file_last_name[1]
            # print("文件名的第二个字符:", last_character)
            if second_character == "L" or second_character == "R":
                newfolder1 = os.path.join("Folder", value["name"])
                os.makedirs(newfolder1, exist_ok=True)
                newfolder2 = os.path.join(newfolder1, folder_time)
                os.makedirs(newfolder2, exist_ok=True)

                new_image_name = "left.jpg" if second_character == "L" else "right.jpg"
                dst_path = os.path.join(newfolder2, new_image_name)
                shutil.copy2(img_file, dst_path)

                if second_character == "L":
                    process_eye_data("0", value, file_last_name)  # 处理左眼数据
                else:
                    process_eye_data("1", value, file_last_name)  # 处理右眼数据

                print(f"Image '{img_file}' copied to {dst_path}")
        else:continue

print("Copying images completed.")
